package com.braveman.im.ui.fragment;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.braveman.im.application.AppApplication;
import com.braveman.im.bean.EmojiconExampleGroupData;
import com.braveman.im.bean.FriendshipListBean;
import com.braveman.im.constant.Constants;
import com.braveman.im.ui.IM.UserDao;
import com.braveman.im.ui.activity.PersonInfoDetailsActivirt;
import com.braveman.im.ui.activity.message.ChatAllActivity;
import com.braveman.im.ui.activity.message.CompanyInfoActivity;
import com.braveman.im.ui.activity.message.GroupInfoActivity;
import com.braveman.im.ui.activity.message.GroupMemberActivity;
import com.braveman.im.ui.activity.mine.GetMineFriendsAndGroupActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseBaiduMapActivity;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.widget.EaseChatExtendMenu;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.easeui.widget.emojicon.EaseEmojiconMenu;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.PathUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class MessageForChatFragment extends EaseChatFragment implements EaseChatFragment.EaseChatFragmentHelper {
    // constant start from 11 to avoid conflict with constant in base class
    private static final int ITEM_VIDEO = 11;
    private static final int ITEM_FILE = 12;
    private static final int ITEM_VOICE_CALL = 13;
    private static final int ITEM_VIDEO_CALL = 14;

    private static final int REQUEST_CODE_SELECT_VIDEO = 11;
    private static final int REQUEST_CODE_SELECT_FILE = 12;
    private static final int REQUEST_CODE_GROUP_DETAIL = 13;
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;
    private static final int REQUEST_CODE_SELECT_AT_USER = 15;


    private static final int MESSAGE_TYPE_SENT_VOICE_CALL = 1;
    private static final int MESSAGE_TYPE_RECV_VOICE_CALL = 2;
    private static final int MESSAGE_TYPE_SENT_VIDEO_CALL = 3;
    private static final int MESSAGE_TYPE_RECV_VIDEO_CALL = 4;
    private static final int MESSAGE_TYPE_RECALL = 9;
    //red packet code : 红包功能使用的常量
    private static final int MESSAGE_TYPE_RECV_RED_PACKET = 5;
    private static final int MESSAGE_TYPE_SEND_RED_PACKET = 6;
    private static final int MESSAGE_TYPE_SEND_RED_PACKET_ACK = 7;
    private static final int MESSAGE_TYPE_RECV_RED_PACKET_ACK = 8;
    private static final int MESSAGE_TYPE_RECV_RANDOM = 11;
    private static final int MESSAGE_TYPE_SEND_RANDOM = 12;
    private static final int ITEM_RED_PACKET = 16;
    static final int ITEM_NAME = 4;

    private static final int MINGPIAN = 31;
    private static final int REQUEST_CODE_SELEST_MINGPIAN = 90;
    private static final int MESSAGE_TYPE_RECV_MINGPIAN_CALL = 5;
    private static final int MESSAGE_TYPE_SENT_MINGPIAN_CALL = 6;
    private boolean isRobot = true;
    private EaseChatFragmentHelper easeChatFragmentHelper;
    private String usrId;
    private int states;


    //end of red packet code

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void setUpView() {
        setChatFragmentHelper(this);
        super.setUpView();
        ((EaseEmojiconMenu) inputMenu.getEmojiconMenu()).addEmojiconGroup(EmojiconExampleGroupData.getData());
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            inputMenu.getPrimaryMenu().getEditText().addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (count == 1 && "@".equals(String.valueOf(s.charAt(start)))) {
                        startActivityForResult(new Intent(getActivity(), GroupMemberActivity.class).
                                putExtra("groupId", toChatUsername), REQUEST_CODE_SELEST_MINGPIAN);
                    }
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SELECT_VIDEO: //send the video
                    if (data != null) {
                        int duration = data.getIntExtra("dur", 0);
                        String videoPath = data.getStringExtra("path");
                        File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
                        try {
                            FileOutputStream fos = new FileOutputStream(file);
                            Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                            ThumbBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                            fos.close();
                            sendVideoMessage(videoPath, file.getAbsolutePath(), duration);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case REQUEST_CODE_SELECT_FILE: //send the file
                    if (data != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            sendFileByUri(uri);
                        }
                    }
                    break;
                case REQUEST_CODE_SELECT_AT_USER:
                    if (data != null) {
                        String username = data.getStringExtra("username");
                        inputAtUsername(username, false);
                    }
                    break;

                case REQUEST_CODE_SELEST_MINGPIAN:
                    if (data != null) {
                        FriendshipListBean friendshipListBean = (FriendshipListBean) data.getSerializableExtra("minpianInfo");

                        String memberName = friendshipListBean.memberName;
                        String userFriendCategoryName = friendshipListBean.userFriendCategoryName;
                        String friendAvater = friendshipListBean.friendAvatar;

                        EMMessage message = EMMessage.createTxtSendMessage(memberName + "的名片", toChatUsername);
                        message.setAttribute(Constants.myExtType, "mingpianType");
                        message.setAttribute(Constants.cardOwnerNickName, memberName);
                        message.setAttribute(Constants.cardOWnerHeaderUrl, friendAvater);
                        EMClient.getInstance().chatManager().sendMessage(message);
                    }
                    break;
            }
        }

    }


    @Override
    public void onSetMessageAttributes(EMMessage message) {
        if (isRobot) {
            // 设置消息扩展属性
            message.setAttribute("em_robot_message", isRobot);
        }
        // 通过扩展属性，将userPic和userName发送出去。
        String userPic = SharedPreferencesUtils.getString(Constants.MINIMG, "");
        if (!TextUtils.isEmpty(userPic)) {
            message.setAttribute("userPic", userPic);
        }
        String userName = SharedPreferencesUtils.getString(Constants.MINNAME, "");
        if (!TextUtils.isEmpty(userName)) {
            message.setAttribute("userName", userName);
        }
    }


    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        super.onMessageReceived(messages);

//        for (EMMessage message : messages) {
//            message.setMsgTime(System.currentTimeMillis());
//            //************接收并处理扩展消息***********************
//            String userName = message.getStringAttribute(Constants.MINNAME, "");
//            String userPic = message.getStringAttribute(Constants.MINIMG, "");
//            String hxIdFrom = message.getFrom();
//            EaseUser easeUser = new EaseUser(hxIdFrom);
//            easeUser.setAvatar(userPic);
//            easeUser.setNick(userName);
//            // 存入内存
//            getContactList();
//            contactList.put(hxIdFrom, easeUser);
//            // 存入db
//            UserDao dao = new UserDao(getContext());
//            List<EaseUser> users = new ArrayList<EaseUser>();
//            users.add(easeUser);
//            dao.saveContactList(users);
//            getModel().setContactSynced(true);
//            // 通知listeners联系人同步完毕
//            notifyContactsSyncListener(true);
//            if (isGroupsSyncedWithServer()) {
//                notifyForRecevingEvents();
//            }
//            // ******************扩展信息处理完成**********************
//            EMLog.d(TAG, "onMessageReceived id : " + message.getMsgId());
//            // 应用在后台，不需要刷新UI,通知栏提示新消息
//            if (!easeUI.hasForegroundActivies()) {
//                getNotifier().onNewMsg(message);
//            }





//            String username = null;
//            // group message
//            if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
//                username = message.getTo();
//            } else {
//                // single chat message
//                username = message.getFrom();
//            }
//
//            // if the message is for current conversation
//            if (username.equals(toChatUsername) || message.getTo().equals(toChatUsername) || message.conversationId().equals(toChatUsername)) {
//                messageList.refreshSelectLast();
//                EaseUI.getInstance().getNotifier().vibrateAndPlayTone(message);
//                conversation.markMessageAsRead(message.getMsgId());
//            } else {
//                EaseUI.getInstance().getNotifier().onNewMsg(message);
//            }
//        }

    }

    @Override
    public void onEnterToChatDetails() {

    }

    @Override
    public void onAvatarClick(String username) {
        /**
         * 用户头像点击事件
         * @param username
         */
        Bundle bundle = new Bundle();
        bundle.putString("user_id", username);
        switch (3) {
            case 1://群
                ActivityUtils.startActivity(getActivity(), GroupInfoActivity.class, bundle);
                break;
            case 2://单位
                ActivityUtils.startActivity(getActivity(), CompanyInfoActivity.class, bundle);
                break;
            case 3://单聊
                ActivityUtils.startActivity(getActivity(), PersonInfoDetailsActivirt.class, bundle);
                break;
        }
    }

    @Override
    public void onAvatarLongClick(String username) {

    }

    @Override
    public boolean onMessageBubbleClick(EMMessage message) {
        return false;
    }

    @Override
    public void onMessageBubbleLongClick(EMMessage message) {

    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        if (itemId == 4) {
            Bundle bundle = new Bundle();
            bundle.putInt("listType", 4);
            ActivityUtils.startActivityForResult(getActivity(), GetMineFriendsAndGroupActivity.class, bundle, REQUEST_CODE_MAP);
            return true;
        }
        return false;
    }

    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
        return null;
    }


}
